package com.zhan.easyexcelnew.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author zhan
 * @since 2021-05-12 15:21
 */
@Slf4j
public class EasyExcelUtils {
    /**consumber相当于是一个消费者 threshold相当于阈值 */
    public static<T> AnalysisEventListener<T> getListener(Consumer<List<T>> consumer, int threshold){
        return new AnalysisEventListener<T>() {
            private LinkedList<T> linkedList = new LinkedList<>();
            @Override
            public void invoke(T t, AnalysisContext analysisContext) {
                linkedList.add(t);
                if(linkedList.size() == threshold){
                    consumer.accept(linkedList);
                    linkedList.clear();
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                log.info("解析到一条数据:{}",linkedList.size());
                if(linkedList.size()>0){
                    consumer.accept(linkedList);
                }
            }
        };
    }

    /**
     * @param consumer
     * @param <T>
     * @return
     */
    public static <T> AnalysisEventListener<T> getListener(Consumer<List<T>> consumer){
        return getListener(consumer,80000);
    }
}
